package com.huanhuan.doc;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.huanhuan.beans.User;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;


public class ESTest_Client_doc_Create {
    public static void main(String[] args) throws Exception{
        final String hostname = "localhost";
        final int port = 9200;
        final String scheme = "http";
        HttpHost httphost = new HttpHost(hostname, port,scheme);
        //创建环境
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder( httphost )
        );

        //插入数据
        IndexRequest indexRequest = new IndexRequest();
        //添加文档的索引和文档的id
        indexRequest.index("user").id("1001");

        User user = new User();
        user.setName( "大欢欢" );
        user.setAge( 18 );
        user.setSex( "女" );

        //因为ES是json格式，必须把他们转换成 json 格式
        ObjectMapper mappers = new ObjectMapper();
        String userJSON = mappers.writeValueAsString( user );
        indexRequest.source( userJSON, XContentType.JSON );

        //创建文档
        IndexResponse indexResponse = client.index( indexRequest, RequestOptions.DEFAULT );
        System.out.println( indexResponse.getResult() );


        client.close();

    }
}
